from rest_framework import serializers
from .models import Story
from accounts.serializers import UserSerializer
from interactions.serializers import CommentSerializer


class StoryListSerializer(serializers.ModelSerializer):
    """故事列表序列化器（简化版）"""
    author_name = serializers.CharField(source='author.name', read_only=True)
    author_id = serializers.IntegerField(source='author.id', read_only=True)
    author_avatar = serializers.SerializerMethodField()
    comments_count = serializers.IntegerField(read_only=True)
    is_liked = serializers.SerializerMethodField()
    is_bookmarked = serializers.SerializerMethodField()
    
    class Meta:
        model = Story
        fields = [
            'id', 'title', 'content', 'category', 'status', 'review_status', 'review_note',
            'author_name', 'author_id', 'author_avatar',
            'tags', 'likes', 'views', 'comments_count', 'is_liked', 'is_bookmarked',
            'created_at', 'updated_at', 'published_at'
        ]
        read_only_fields = ['id', 'likes', 'views', 'created_at', 'updated_at']
    
    def get_author_avatar(self, obj):
        """获取作者头像URL"""
        if obj.author.avatar:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.author.avatar.url)
            return obj.author.avatar.url
        return '/media/avatars/default.png'
    
    def get_is_liked(self, obj):
        """是否已点赞"""
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            from interactions.models import Like
            return Like.objects.filter(user=request.user, story=obj).exists()
        return False
    
    def get_is_bookmarked(self, obj):
        """是否已收藏"""
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            from interactions.models import Bookmark
            return Bookmark.objects.filter(user=request.user, story=obj).exists()
        return False
    
    def get_comments_count(self, obj):
        """获取评论数量"""
        return obj.comments.count()


class StoryDetailSerializer(serializers.ModelSerializer):
    """故事详情序列化器（完整版）"""
    author_name = serializers.CharField(source='author.name', read_only=True)
    author_id = serializers.IntegerField(source='author.id', read_only=True)
    author_avatar = serializers.SerializerMethodField()
    comments_count = serializers.IntegerField(read_only=True)
    comments = serializers.SerializerMethodField()
    is_liked = serializers.SerializerMethodField()
    is_bookmarked = serializers.SerializerMethodField()
    
    class Meta:
        model = Story
        fields = [
            'id', 'title', 'content', 'category', 'status', 'review_status', 'review_note',
            'author_name', 'author_id', 'author_avatar',
            'tags', 'likes', 'views', 'comments_count', 'comments', 'is_liked', 'is_bookmarked',
            'created_at', 'updated_at', 'published_at'
        ]
        read_only_fields = ['id', 'likes', 'views', 'created_at', 'updated_at']
    
    def get_author_avatar(self, obj):
        """获取作者头像URL"""
        if obj.author.avatar:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.author.avatar.url)
            return obj.author.avatar.url
        return '/media/avatars/default.png'
    
    def get_is_liked(self, obj):
        """是否已点赞"""
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            from interactions.models import Like
            return Like.objects.filter(user=request.user, story=obj).exists()
        return False
    
    def get_is_bookmarked(self, obj):
        """是否已收藏"""
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            from interactions.models import Bookmark
            return Bookmark.objects.filter(user=request.user, story=obj).exists()
        return False
    
    def get_comments_count(self, obj):
        """获取评论数量"""
        return obj.comments.count()
    
    def get_comments(self, obj):
        """获取评论列表"""
        comments = obj.comments.select_related('author').order_by('-created_at')
        return CommentSerializer(comments, many=True, context=self.context).data


class StoryCreateSerializer(serializers.ModelSerializer):
    """故事创建/更新序列化器"""
    class Meta:
        model = Story
        fields = ['title', 'content', 'category', 'status', 'tags']
    
    def create(self, validated_data):
        """创建故事，自动设置作者"""
        request = self.context.get('request')
        validated_data['author'] = request.user
        return super().create(validated_data)


class StoryGenerateSerializer(serializers.Serializer):
    """AI生成故事参数序列化器"""
    prompt = serializers.CharField(max_length=200, required=True)
    category = serializers.CharField(max_length=20, required=True)
    word_count = serializers.IntegerField(default=500, min_value=100, max_value=2000)
    
    def validate_category(self, value):
        """验证分类是否有效"""
        valid_categories = [choice[0] for choice in Story.CATEGORY_CHOICES]
        if value not in valid_categories:
            raise serializers.ValidationError(f"无效的分类，有效分类: {', '.join(valid_categories)}")
        return value
